package org.n.shop.service.impl;

import lombok.AllArgsConstructor;
import org.n.shop.domain.entity.Address;
import org.n.shop.mapper.AddressMapper;
import org.n.shop.result.RestResult;
import org.n.shop.result.RestResultBuilder;
import org.n.shop.service.AddressService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import static org.n.shop.config.RedisConfig.PREFIX_USER;

@Service
@AllArgsConstructor
public class AddressServiceImpl implements AddressService {
    private AddressMapper addressMapper;
    private RedisTemplate redisTemplate;

    @Override
    public RestResult all(String authorization) {
        int userId = (int) redisTemplate.opsForValue().get(PREFIX_USER + authorization);
        return new RestResultBuilder().success(
                addressMapper.all(userId)
        );
    }

    @Override
    public RestResult add(String authorization, Address address) {
        int userId = (int) redisTemplate.opsForValue().get(PREFIX_USER + authorization);
        address.setUserId(userId);

        if (address.getName() == null) {
            address.setName(address.getConsignee() + address.getAddress().substring(0, 2));
        }

        if (addressMapper.add(address) == 1) {
            return new RestResultBuilder().success();
        }
        return new RestResultBuilder().fail("新增失败");
    }

    @Override
    public RestResult update(Address address) {
        if (addressMapper.update(address) == 1) {
            return new RestResultBuilder().success();
        }
        return new RestResultBuilder().fail("更新失败");
    }

    @Override
    public RestResult del(int id) {
        if (addressMapper.del(id) == 1) {
            return new RestResultBuilder().success();
        }
        return new RestResultBuilder().fail("删除失败");
    }

    @Override
    public RestResult setDefault(String authorization, int id) {
        int userId = (int) redisTemplate.opsForValue().get(PREFIX_USER + authorization);
        if (addressMapper.setDefault(userId, id) != null) {
            return new RestResultBuilder().success();
        }
        return new RestResultBuilder().fail("更新失败");
    }
}
